<template>
  <div>
    <!-- 钢瓶归属变更记录 -->
    <el-table-form ref="form" :model="query">
      <el-form-item label="操作时间:" :table-form-merge="2">
        <el-date-picker
          v-model="date"
          clearable
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
          :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <el-form-item label="发生机构:" prop="orgId">
        <el-tree-select
          v-model="query.orgId"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgId',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
        />
      </el-form-item>
      <el-form-item label="气瓶编号:" prop="chipCode">
        <el-input v-model="query.chipCode" />
      </el-form-item>
      <template v-slot:btns>
        <el-button v-permission="[70105,1]" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <!-- <div style="margin-bottom: 10px;" class="btn-group">
      <el-button
        v-permission="12"
        type="primary"
        icon="el-icon-download"
        :loading="$loadingPlugin.batchExp"
        @click="batchExp"
      >导出</el-button>
    </div> -->
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <order-detail
      ref="orderDetail"
      :payment-method-map="paymentMethodMap"
      :pay-status-map="payStatusMap"
      :order-flag-map="orderFlagMap"
      :order-source-map="orderSourceMap"
      :order-status-map="orderStatusMap"
      :transactor-list="transactorList"
    />
    <cylinderDetail ref="cylinderDetail" />
  </div>
</template>

<script>
  import { parseTime } from '@/utils'
  import { queryInvenChipChangeList, queryMap } from '@/api'
  //   import { mapGetters } from 'vuex'
  import moment from 'dayjs'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import orderDetail from '../../../orderCenter/orderManage/components/OrderDetails.vue'
  import CylinderDetail from '@/views/components/cylinderDetail/index'

  export default {
    name: 'cylinderChangeRecord',
    components: {
      orderDetail, CylinderDetail
    },
    props: {
      treeData: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        txt: '',
        date: [new Date(new Date().setHours(0, 0, 0, 0)), new Date(new Date().setHours(0, 0, 0, 0) + 24 * 60 * 60 * 1000 - 1)],
        searchParams: {},
        query: {
          orgId: '',
          chipCode: ''
        },
        tableData: {
          total: 0,
          data: []
        },
        paymentMethodMap: [],
        payStatusMap: [],
        orderFlagMap: [],
        orderSourceMap: [],
        orderStatusMap: [],
        transactorList: []
      }
    },
    computed: {
      //   ...mapGetters([
      //     'exportDomain'
      //   ]),
      column: function() {
        const cols = [
          {
            type: 'index'
          },
          {
            prop: 'chipCode',
            label: '气瓶芯片号',
            width: 110,
            render: (h, { row }) => (<el-link underline={false} onClick={() => this.showCylinderDetail(row.chipCode)}>{row.chipCode}</el-link>)
          },
          {
            prop: 'operateTime',
            label: '操作时间',
            width: 160,
            render: (h, { row }) => row.operateTime && <span>{ parseTime(row.operateTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'orgName',
            width: 200,
            label: '发生机构'
          },
          {
            prop: 'operateName',
            label: '操作人'
          },
          {
            prop: 'csmNameBefore',
            label: '变更前客户名称',
            minwidth: 140
          },
          {
            prop: 'operateNameBefore',
            label: '变更前处理人',
            minwidth: 140
          },
          {
            prop: 'csmNameAfter',
            label: '变更后客户名称',
            minwidth: 140
          },
          {
            prop: 'orderCode',
            label: '匹配订单',
            width: 110,
            render: (h, { row }) => (<el-link underline={false} onClick={() => this.openOrderDetail(row)}>{row.orderCode}</el-link>)
          }
        ]
        return cols
      }
    },
    mounted() {
      this.queryOptionsMap()
    },
    methods: {
      // 查询枚举
      async queryOptionsMap() {
        const [res1, res2, res3, res4, res5, res6, res7] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'OrderStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderFlag' }),
          mergeAsyncFunc(queryMap, { enumName: 'CustomerType' }),
          mergeAsyncFunc(queryMap, { enumName: 'PayStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' }),
          mergeAsyncFunc(queryMap, { enumName: 'ReStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderSource' })
        ])
        this.orderStatusMap = res1.data.filter((item) => item.value !== 6) // 订单类型(去掉‘已转派’)
        this.orderFlagMap = res2.data // 订单类型
        this.customerTypeMap = res3.data // 客户类型
        this.payStatusMap = res4.data // 支付状态
        this.paymentMethodMap = res5.data.filter(item => item.value === 1 || item.value === 2 || item.value === 16 || item.value === 128 || item.value === 256 || item.value === 2048) // 支付方式
        this.reStatusMap = res6.data // 回执状态
        this.orderSourceMap = res7.data // 订单来源
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage = 1, pageSize = 20 }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (this.date && this.date.length === 2) {
          query.operateTimeBegin = moment(this.date[0]).format()
          query.operateTimeEnd = moment(this.date[1]).format()
        }
        this.searchParams = {
          ...query
        }
        const res = await queryInvenChipChangeList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 气瓶详情
      async showCylinderDetail(val) {
        if (val) {
          await this.$refs.cylinderDetail.open(val)
        } else {
          this.$message.warning('暂无相关信息')
        }
      },
      async openOrderDetail(row) {
        await this.$refs.orderDetail.open(row)
      }
      // 导出
    //   batchExp() {
    //     const _this = this
    //     this.$confirm(`确定导出数据？`, '提示', {
    //       type: 'warning'
    //     }).then(() => {
    //       const copyColumn = JSON.parse(JSON.stringify(this.column))
    //       const str = {}
    //       copyColumn.forEach((item) => {
    //         str[item.prop] = item.label
    //       })
    //       const params = this.searchParams
    //       const paramInfo = _this._getQuery(params)
    //       callorBottleExport({
    //         paramInfo: paramInfo,
    //         kv: str // 表格列
    //       }).then((res) => {
    //         window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
    //       })
    //     })
    //   }
    }
  }
</script>

<style lang="scss" scoped>
/deep/.el-form-item {
  margin-bottom: 10px;
}
.disabled {
  color: #909399 !important;
}
.footText {
  position: absolute;
  right: 10px;
  bottom: 5px;
  color: #F56C6C;
}
</style>
